<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input v-model="queryData.username" placeholder="搜索"></el-input>
        </el-col>
        <el-col :span="1">
          <el-button @click="getUserList" class="btn_search" type="primary">搜索</el-button>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="resetInfo">重置</el-button>
        </el-col>
      </el-row>
      <!-- 新增用户区域 -->
      <el-button @click="adduserdig" class="addUser" type="primary" icon="el-icon-edit" size="mini">新增用户</el-button>
      <!-- 消息提示文案 共几条数据 -->
       <el-alert
        type="info"
        show-icon
        :closable="false"
        >
          <template slot="title">
            共{{ total }}条记录
          </template>
        </el-alert>
      <!-- 表格部分 -->
        <el-table class="table" :data="list" border style="width: 100%">
          <el-table-column type="index" label="序号" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="phone" label="联系电话"></el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="permission_group_title" label="权限名称"></el-table-column>
          <el-table-column prop="role" label="角色"></el-table-column>
          <el-table-column prop="operating" label="操作">
            <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button @click="showeditUser(scope.row)" type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除 -->
            <el-button @click="removeUser(scope.row)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
          </template>
          </el-table-column>
        </el-table>

      <!-- 分页功能 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="fenye">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="adddialogVisible"
      width="50%">
       <el-form :rules="addRule" ref="addForm" :model="addUserForm" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="role" label="角色">
          <el-input v-model="addUserForm.role"></el-input>
        </el-form-item>
        <el-form-item prop="permission_group_id" label="权限名称">
          <el-select v-model="addUserForm.permission_group_id" placeholder="请选择">
            <el-option
              v-for="item in optionsList"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="addUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item prop="introduction" label="介绍">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="Please input"
            v-model="addUserForm.introduction">
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editdialogVisible"
      width="50%">
      <el-form :rules="editRule" ref="editForm" :model="editUserForm" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="editUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="role" label="角色">
          <el-input v-model="editUserForm.role"></el-input>
        </el-form-item>
        <el-form-item label="权限名称">
          <el-select v-model="editUserForm.permission_group_id" placeholder="请选择">
             <el-option
              v-for="item in optionsList"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="editUserForm.phone"></el-input>
        </el-form-item>
        <el-form-item prop="introduce" label="介绍">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="Please input"
            v-model="editUserForm.introduce">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserCommit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, update, remove } from '@/api/base/users.js'
import { simple } from '@/api/base/permissions.js'
export default {
  name: 'user',
  data () {
    // 1.邮箱的自定义校验规则
    const checkEmail = (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        // 校验成功直接返回
        callback()
      } else {
        callback(new Error('邮箱格式不正确'))
      }
    }
    return {
      list: [],
      queryData: {
        keyword: '',
        page: 1,
        pagesize: 8,
        username: ''
      },
      total: 0,
      // 控制添加对话框是否显示隐藏
      adddialogVisible: false,
      editdialogVisible: false,
      // 添加用户数据
      addUserForm: {
        avatar: '',
        email: '1123@qq.com',
        introduction: '这是一个介绍',
        password: '123456',
        permission_group_id: '',
        phone: '13111111111',
        role: '组长111',
        username: '陈独秀'
      },
      optionsList: [],
      // 编辑用户数据
      editUserForm: {},
      // 验证必填表单
      addRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
      },
      editRule:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    // 获取用户列表
    async getUserList () {
      const res = await list(this.queryData)
      if (res.status !== 200) return this.$toast.fail('获取失败')
      this.total = res.data.counts
      this.list = res.data.list
      // console.log(res)
    },

    // 每页条数发生变化
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUserList()
    },
    // 页码发生变化
    handleCurrentChange (val) {
      this.queryData.page = val
      this.getUserList()
    },

    // 获取权限名称
    async adduserdig () {
      this.adddialogVisible = true
      const { data: res } = await simple()
      this.optionsList = res
      // console.log(res)
    },
    // 添加用户
    addUser () {
      this.$refs.addForm.validate(async flag => {
        if (!flag) return
        // console.log('表单合法发送请求')
        try {
          const res = await add(this.addUserForm)
          this.getUserList()
          this.adddialogVisible = false
          this.$message.success('添加用户成功')
        } catch (err) {
          if (status !== 200) this.$message.error('添加用户失败')
        }
        // console.log(res)
      })
    },

    // 编辑用户
    async showeditUser (row) {
      this.editdialogVisible = true
      this.editUserForm = row
      const { data: res } = await simple()
      this.optionsList = res
      // console.log(row)
    },

    // 编辑用户点击提交
    async editUserCommit () {
      delete this.editUserForm.permission_group_title
      delete this.editUserForm.create_time
      delete this.editUserForm.introduce
      delete this.editUserForm.is_deleted
      delete this.editUserForm.last_update_time
      try {
        await update(this.editUserForm)
        this.editdialogVisible = false
        this.getUserList()
        this.$message.success('更新成功')
      } catch (err) {
        this.$message.error('更新失败')
      }
      // console.log(res)
    },

    // 删除用户
    removeUser (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await remove(row)
        console.log(row)
        if (res.status !== 200) return this.$message.error('删除用户失败')
        // console.log(res)
        this.$message.success('删除用户成功')
        this.getUserList()
      }).catch(() => {
        this.$message('已取消删除失败')
      })
    },

    // 重置表单信息
    resetInfo () {
      this.queryData.username = ''
      this.getUserList()
    }
  }
}
</script>

<style scoped lang='less'>
/deep/.box-card {
  position: relative;
  margin: 20px 20px;
  padding-bottom: 40px;
  .btn_search {
    margin-left: -20px;
    margin-right: 10px;
  }
  .addUser {
    position: absolute;
    right: 20px;
    margin-top: 30px;
  }
  .el-alert {
    margin-top: 70px;
  }
  .table {
    margin-top: 30px;
  }
  .fenye {
    margin-top: 30px;
  }
}
</style>
